var freeswitchUser;

var myUA;

var incomingSession;

var timeOutTask;

var  interval;

var session;

function initUa(password) {
    alert(freeswitchWs);
    var uaConfig = {
        uri: freeswitchUser + "@"+userurl,
        wsServers: freeswitchWs,
        authorizationUser: freeswitchUser,
        displayName: freeswitchUser,
        password: password,
        log: {
            builtinEnabled: false
            //level:"debug"
        },
        //traceSip:true,
        register: true,
    };
    /*alert(uaConfig.wsServers);
    alert(uaConfig.password);*/
    //location.prototype.assign(uaConfig.uri);
   // console.log("uaConfig:"+uaConfig.wsServers+"uri:"+uaConfig.uri+":authorizationUser:"+uaConfig.authorizationUser);
    myUA = new SIP.UA(uaConfig);
    //myUA.transport.wsServers = freeswitchWs;

    //ws链接成功调用
    myUA.on("connected", function () {
        console.log("freeswitchLog:  websocket连接成功: " + uaConfig.wsServers);
    });
    console.log("uaConfig:"+uaConfig.wsServers+"url:"+uaConfig.url+":authorizationUser:"+uaConfig.authorizationUser);
//ws链接失败调用
    myUA.on("disconnected", function () {
        console.log("freeswitchLog:  websocket连接失败: " + uaConfig.wsServers);
    });

//注册成功调用
    myUA.on("registered", function () {
        console.log("freeswitchLog:  " + uaConfig.authorizationUser + "用户注册成功");
        upgradeDOM();

        //先清除旧的定时任务,再重新执行
        window.clearInterval(interval);
        setUAInterval();
    });

//取消时候调用
    myUA.on("unregistered", function () {
        console.log("freeswitchLog:  " + uaConfig.authorizationUser + "用户取消注册");
        window.clearInterval(interval);
    });


    /**
     *接受入站
     */
    myUA.on("invite", function (thisIncomingSession) {

        incomingSession=thisIncomingSession;

        initSession(incomingSession);

    });



}

/**
 * 设置定时任务,每隔20秒检测
 */
function setUAInterval() {

    console.log("freeswitchlog:  开启定时检测UA任务")

    interval=setInterval("checkUAStatus()", 20000)
}

/**
 * 定时检测UA的健康
 */
function checkUAStatus() {
    if (myUA != null && myUA != undefined) {
        var isConnected = myUA.isConnected();
        var isRegistered = myUA.isRegistered();

        if (!isConnected || !isRegistered) {
            console.log("freeswitchLog:  连接或者注册异常,将重新连接")
            myUA.start();
        } else {
            console.log("freeswitchLog:  连接和注册正常,每20秒检测一次")
            //myUA.register();
        }
    }

}

/**
 * 点击登录
 */
$("#login").click(function () {

    if ($("#login").val() == "登录") {
        freeswitchUser = $("#mainCallPhone").val();

        //先发请求到后台,看此号码有没有人登录
        /*$.ajax({
            url:"https://"+callService+"/freeswitch/checkUser",
            data:{"user":freeswitchUser},
            dataType:"json",
            success:function (callBackData) {

                if(callBackData.code=="success"){

                    if(callBackData.parameter){
                        initUa($("#password").val());
                    }else {
                        alert("当前用户已被使用,请更换用户")
                    }
                }else {

                    alert("服务器正忙,请稍后重试")
                }
            }
        });*/

        initUa($("#password").val());

    } else if ($("#login").val() == "注销") {
        myUA.unregister();
        myUA = null;
        demotionDom()
    }

})

/**
 * 渲染页面
 */
function upgradeDOM() {
    $("#status").text("已登录").css("color", "green");
    $(".initDom").attr("disabled", false);
    $("#callBtn,#interrupCall").css("display", "inline");
    $("#passwordTr").hide();
    $("#login").val("注销");
    $("#mainCallPhone").attr("readonly", true);
    clearTimeout(timeOutTask);
}

/**
 * 页面恢复初始状态
 */
function demotionDom() {
    $("#status").text("未登录").css("color", "red");
    $(".initDom").attr("disabled", true);
    $("#callBtn,#interrupCall").css("display", "none");
    $("#passwordTr").show();
    $("#login").val("登录");
    $("#mainCallPhone").attr("readonly", false);
}

/**
 * 初始化Session
 */
function initSession(initSession) {

    initSession.accept({
        media: {
            constraints: {audio: true,video:false},

            render: {
                remote: {audio: $("#remoteAudio").get(0)},
                local:  {audio:$("#localAudio").get(0)}
            },

            RTCConstraints: {"optional": [{'DtlsSrtpKeyAgreement': 'true'}]}
        }
    });

    initSession.on("accepted", function (data) {
        console.log("freeswitchLog: 收到请求成功的最终回复:"+data.substr(data.search(/[2][0-9][0-9]/),3));
        clearTimeout(timeOutTask);
        outgoingStop()
    })

    initSession.on("connecting", function () {
        console.log("freeswitchLog:  通话正在连接被叫");
        outgoingRing();
        timeOutTask = setTimeout(connectTimeOut(inComingSession), 30000);
    })

    initSession.on("rejected", function (response, cause) {
        console.log("freeswitchLog:  通话已拒绝");
        initBtnAndsounds()
    })

    initSession.on('bye', function (request) {
        console.log("freeswitchLog:  通话结束");
        initBtnAndsounds()
    })

    initSession.on('cancel', function (request) {
        console.log("freeswitchLog:  通话被终止");
        initBtnAndsounds()
    })


    initSession.on('failed', function (request) {
        console.log("freeswitchLog: 通话建立失败")
        initBtnAndsounds()
    })
    session = initSession;
}

/**
 * 铃声停止
 */
function outgoingStop() {

    $("#bell").get(0).pause();
}

/**
 *铃声开始
 */
function outgoingRing(){
    $("#bell").get(0).play();
};

/**
 * 响铃太久
 * @param inComingSession
 */
function connectTimeOut() {

    if (incomingSession == null || incomingSession == undefined) {
        console.log("freeswitchLog:  连接超过30秒,通话将自动关闭");
        outgoingStop();
    } else {
        console.log("freeswitchLog:  连接超过30秒,通话将自动关闭");
        incomingSession.bye();
        incomingSession=null;
        outgoingStop();
    }
    $("#callBtn").css("display","inline-block");
}